<?php

namespace app\health\model;

use app\health\service\AdsApi;
use app\health\service\EquityCenterService;
use app\health\service\WePayService;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\DbException;
use think\Model;

/**
 * 支付中心模型
 * @Author 张旭鹏
 * @DateTime 2023-07-06
 */
class HealthPayment extends Model
{
	// 表名
	protected $name               = 'health_payment';
	protected $autoWriteTimestamp = 'datetime';

	protected $dateFormat = 'Y-m-d H:i:s';

	// 定义时间戳字段名
	protected $createTime = 'created_at';
	protected $updateTime = 'updated_at';

	protected $insert = ['out_trade_no'];

	protected $append = ['pay_status_text'];

	// 微信支付
	public const PAY_WAY_WECHAT = 1;
	// 余额支付
	public const PAY_WAY_BALANCE = 0;

	public const PAY_STATUS_MAP = [
		0 => '待支付',
		1 => '已支付',
		2 => '已关闭'
	];


	/**
	 * 生成支付订单号
	 * @return string
	 * @Author 张旭鹏
	 * @DateTime 2023-07-06
	 */
	public function setOutTradeNoAttr()
	{
		return create_trade_no('P');
	}

	/**
	 * 支付状态描述
	 * @param [type] $val
	 * @param [type] $data
	 * @return string
	 * @Author 张旭鹏
	 * @DateTime 2023-07-06
	 */
	public function getPayStatusTextAttr($val, $data)
	{
		return self::PAY_STATUS_MAP[$data['pay_status']];
	}


	/**
	 * 创建微信支付参数
	 * @param HealthPayment $healthPayment
	 * @param [type] $openid
	 * @Author 张旭鹏
	 * @DateTime 2023-07-06
	 */
	public static function createdWechatPay(HealthPayment $healthPayment, $openid)
	{
		// 生成支付参数
		$wechatPayParams = [
			'body'         => $healthPayment['pay_description'],
			'out_trade_no' => $healthPayment['out_trade_no'],
			'total_fee'    => bcmul($healthPayment['pay_money'], 100),
			'openid'       => $openid,
			'trade_type'   => 'JSAPI',
			'attach'       => 'mode=payment',
			'notify_url'   => request()->domain() . '/health/notify/wepay',
		];
		return WePayService::WePayOrder()->create($wechatPayParams);
	}

	/**
	 * 支付成功回调
	 * @param HealthPayment $healthPayment
	 * @return true
	 * @throws DataNotFoundException
	 * @throws ModelNotFoundException
	 * @throws DbException
	 * @Author 张旭鹏
	 * @DateTime 2023-07-06
	 */
	public static function paySuccess(HealthPayment $healthPayment): bool
	{
		if ((int)$healthPayment['type'] === 1) {
			EquityCenterService::orderNotify($healthPayment['order_no']);
            $healthBusiness=HealthBusiness::where('order_no', $healthPayment['order_no'])->where('zf_code', 'annual_card')->find();
            if($healthBusiness){
                HealthBusiness::where('order_no', $healthPayment['order_no'])->where('zf_code', 'annual_card')->update(['status' => 2]);
                HealthBusinessAccess::where('request_id', $healthBusiness['request_id'])->update(['status' => 2]);
                self::adsApi([
                    'clickid'=>$healthBusiness['click_id'],
                    'mobile'=>$healthBusiness['mobile'],
                    'pid'=>$healthBusiness['channel'],
                    'url'=>$healthBusiness['url'],
                    'zfCode'=>$healthBusiness['zf_code'],
                ]);
            }
		}
		if ((int)$healthPayment['type'] === 2) {
			HealthFuluOrder::paySuccess($healthPayment['order_no']);
		}
		return true;
	}

    /**
     * @Desc:广告平台回传
     * @param $params
     * @author: hff
     * @Time: 2023/11/8 11:05
     */
    public static function adsApi($params)
    {
        if (empty($params['clickid'])) {
            return;
        }
        $clickid = $params['clickid'];
        //广告平台api回传
        if (!empty($clickid)) {
            if ($params['platform'] == 'tx') {//腾讯广告
                AdsApi::TxApi('RESERVATION', $clickid, $params['mobile'], $params['pid'], $params['url'], $params['zfCode']);
            } else if($params['platform']=='txmini'){
                AdsApi::TxMiniApi('COMPLETE_ORDER',$params['clickid'],$params['mobile'],$params['pid'],$params['url'],$params['zfCode']);
            }else {
                AdsApi::JlApi('form', $clickid, $params['mobile'], $params['pid'], $params['url'], $params['zfCode']);
            }
        }
    }
}
